package appconfig

/*
 * @Author: huangchangqing
 * @Description: app的配置文件的go文件
 */
import (
	"github.com/BurntSushi/toml"
	"github.com/gin-gonic/gin"
	"local.public/innerpkg/logger"
	"path/filepath"
	"reflect"
	"sync"
)

// 配置文件对应的结构体
type AppTomlConfig struct {
	Listen struct {
		Port int `toml:"port"`
	}

	Mqtt struct {
		ClientId       string `toml:"clientid"`
		LocalStationId string `toml:"local_station_id"`
	} `toml:"mqtt"`

	LimitOptions struct {
		ClientIdPrefixArr  []string `toml:"clientid_prefix_arr"`
		ClientIdExcludeArr []string `toml:"clientid_exclude_arr"`
		FrameworkArr       []string `toml:"framework_arr"`
	} `toml:"limitoptions"`
}

var configApp AppTomlConfig
var onceApp sync.Once

func printAppSectionDetail(stu interface{}) {
	var typeInfo = reflect.TypeOf(stu)
	var valInfo = reflect.ValueOf(stu)
	num := typeInfo.NumField()
	for i := 0; i < num; i++ {
		logger.Debug(typeInfo.Field(i).Name, "=", valInfo.Field(i))
	}
}

func GetConfig() *AppTomlConfig {
	onceApp.Do(func() { //配置文件只读取一次
		cfgFilePath, err := filepath.Abs("./conf/app.toml")
		if err != nil {
			logger.Debug("未获取到conf/app.toml的绝对路径", err)
			return
		}
		//utils.Debug("parse toml file. filePath: %s\n", cfgFilePath)
		if _, err := toml.DecodeFile(cfgFilePath, &configApp); err != nil {
			logger.Debug("toml文件解码失败", err)
			return
		}
		if gin.DebugMode == "debug" {
			printAppSectionDetail(configApp.Listen)
		}
	})
	return &configApp
}
